package com.xy.hms.controller;


import com.xy.hms.model.Room;
import com.xy.hms.service.RoomServiceI;
import com.xy.hms.util.DataUtil;
import com.xy.hms.util.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaye
 * @create 2020-02-25-16:36
 */
@Api(tags = "房间相关")
@Controller
@Slf4j
public class RoomController {

    @Autowired
    public RoomServiceI roomServiceI;

    //跳转到所有房间页面
    @ApiOperation("跳转到所有房间页面")
    @GetMapping("/rooms")
    public String getAllRooms(Model model){

        List<Room> rooms = roomServiceI.selectAllRooms();
        model.addAttribute("allrooms",rooms);
        return "room/all_rooms";
    }

    //跳转至添加页面
    @GetMapping("/room")
    public String toAddPage(){
        return "room/add_room";
    }


    //房间添加
    @PostMapping("/room")
    public String addRoom( Room room,Model model){
        try {
            System.out.println(room);
            String message = roomServiceI.insertRoom(room);
            return "redirect:/rooms";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failadd",e.getMessage());
            return "room/add_room";
        }
    }

    //跳转房间修改回显数据
    @GetMapping("/room/{rid}")
    @ResponseBody
    public DataUtil toEditPage(@PathVariable("rid")Integer rid, DataUtil dataUtil){


        //回显这个需要需改的房间信息
        Room toUpdateroom = roomServiceI.selectRoomByid(rid);
//        model.addAttribute("toModifty",toModiftyroom);
        ArrayList<Room> toUpdaterooms = new ArrayList<>();
        toUpdaterooms.add(toUpdateroom);
        dataUtil.setData(toUpdaterooms);
        dataUtil.setResult(true);
        return dataUtil;
    }


    //房间修改
    @PutMapping("room")
    @ResponseBody
    public DataUtil updateRoom(Room room,DataUtil dataUtil){
        log.error(room.toString());

        try {
            //修改成功
            String message = roomServiceI.updateRoom(room);
            dataUtil.setMsg(message);
            dataUtil.setResult(true);
        } catch (Exception e) {
            //修改失败
            e.printStackTrace();
            dataUtil.setResult(false);
            dataUtil.setMsg(e.getMessage());
        }
        return dataUtil;
    }

    //员工删除
    @DeleteMapping("/room/{rid}")
    public String deleteRoom(@PathVariable("rid")Integer rid,Model model){

        try {
            //删除成功
            String s = roomServiceI.deleteRoom(rid);
            model.addAttribute("msg",s);
        } catch (Exception e) {
            //删除失败
            model.addAttribute("msg",e.getMessage());
        }
        return "redirect:/rooms";
    }



}
